﻿using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Transitionals;

namespace ViewLED.UI
{
    /// <summary>
    /// Ppicture.xaml 的交互逻辑
    /// </summary>
    public partial class Ppicture : Page
    {
        Screen scr; // 定义一个子窗体，用于在屏幕指定区域播放显示内容
        int[] switchTime = new int[7] { 1, 2, 3, 5, 7, 10, 20 }; // 切换时间选项（单位：秒）

        private ObservableCollection<Type> transitionTypes = new ObservableCollection<Type>();
        // 创建计时器
        DispatcherTimer timer = null;
        ArrayList list = new ArrayList();
        int s = 0;        //记录播放的张数
        bool which = true;  //记录当前显示的iA还是iB
        UI.ImgEle iA = new ImgEle();
        UI.ImgEle iB = new ImgEle();

        bool mutex = true; // 记录下拉显示的变更是鼠标选择还是添删记录造成的标识变量

        public Ppicture()
        {
            InitializeComponent();
            LoadTransitions(Assembly.GetAssembly(typeof(Transition)));
            // 读取上次缩放类型、速度的设置
            cbxType.SelectedIndex = int.Parse(ConfigurationManager.AppSettings["ImageStretchMode"]);
            cbxSpeed.SelectedIndex = int.Parse(ConfigurationManager.AppSettings["SwitchTime"]);
            getPicFile();
            list = Model.FileExplorer.listFile("Picture", true);
            if (list.Count > 0)
            {
                changetimer_Tick(null, null);
                setAutoChangeImg();
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("请至少添加一个文件才能预览效果！", "错误提示");
            }
        }

        // 读取文件列表放到下拉菜单中
        public void getPicFile()
        {
            cbxPreview.ItemsSource = Model.FileExplorer.listFile("Picture", false);
        }

        public void setAutoChangeImg()
        {
            // 设置自动切换计时器
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(switchTime[int.Parse(ConfigurationManager.AppSettings["SwitchTime"])]);
            timer.Tick += new EventHandler(changetimer_Tick);
            timer.Start();
        }
         
        void selTrans()
        {
            // 随机选择一种切换特效
            int m_nIndex = 0;
            m_nIndex = new Random().Next(0, transitionTypes.Count);
            Type transitionType = transitionTypes[m_nIndex];
            Transition t = (Transition)Activator.CreateInstance(transitionType);
            mainp.Transition = t;
        }

        private void changetimer_Tick(object sender, EventArgs e)
        {
            if(timer != null)
                timer.Interval = TimeSpan.FromSeconds(switchTime[int.Parse(ConfigurationManager.AppSettings["SwitchTime"])]);
            selTrans();
            GC.Collect();
            if (which)
            {
                Uri uri = new Uri(list[s % list.Count].ToString(), UriKind.Absolute);
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.UriSource = uri;
                image.EndInit();
                iB.Img = image;
                iB.StretchType = cbxType.SelectedIndex;
                mainp.Content = iB;
                which = false;
            }
            else
            {
                Uri uri = new Uri(list[s % list.Count].ToString(), UriKind.Absolute);
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.UriSource = uri;
                image.EndInit();
                iA.Img = image;
                iA.StretchType = cbxType.SelectedIndex;
                mainp.Content = iA;
                which = true;
            }
            s = (s + 1) % list.Count;
        }

        // 加载特效库
        public void LoadTransitions(Assembly assembly)
        {
            foreach (Type type in assembly.GetTypes())
            {
                if (transitionTypes.Contains(type)) { continue; }

                if ((typeof(Transition).IsAssignableFrom(type)) && (!type.IsAbstract))
                {
                    transitionTypes.Add(type);
                }
            }
        }

        // 速度变化
        private void cbxSpeed_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Model.FileExplorer.setConfig("SwitchTime", cbxSpeed.SelectedIndex.ToString());
        }

        private void cbxType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 对前后两张图设置缩放类型
            iB.StretchType = cbxType.SelectedIndex;
            iA.StretchType = cbxType.SelectedIndex;
            Model.FileExplorer.setConfig("ImageStretchMode", cbxType.SelectedIndex.ToString());
        }

        // 单独预览某一项
        private void cbxPreview_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(mutex)
            {
                list.Clear();
                string p = System.AppDomain.CurrentDomain.BaseDirectory + "Picture\\" + cbxPreview.SelectedValue.ToString();
                if (File.Exists(p))
                {
                    list.Add(System.AppDomain.CurrentDomain.BaseDirectory + "Picture\\" + cbxPreview.SelectedValue.ToString());
                }
            }
        }

        // 删除指定项目
        private void removeItem(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory + "Picture\\";
            fd.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp";
            fd.Multiselect = false;
            if (fd.ShowDialog() == DialogResult.OK && fd.FileName.IndexOf(fd.InitialDirectory) == 0)
            {
                mutex = false;
                list.Remove(fd.FileName);
                if (Model.FileExplorer.removeFile("Picture\\" + fd.SafeFileName))
                {
                    list.Remove(fd.FileName);
                    getPicFile();
                }
                mutex = true;
            }
        }

        // 添加新项目
        private void addNewItem(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp";
            fd.Multiselect = false;
            if (fd.ShowDialog() == DialogResult.OK)
            {
                mutex = false;
                if (Model.FileExplorer.addFile(fd.FileName, System.AppDomain.CurrentDomain.BaseDirectory + "Picture\\" + fd.SafeFileName))
                {
                    list = Model.FileExplorer.listFile("Picture", true);
                    getPicFile();
                }
                mutex = true;
            }           
        }

        // 恢复完整播放
        private void resetPlay(object sender, RoutedEventArgs e)
        {
            mutex = false;
            list = Model.FileExplorer.listFile("Picture", true);
            getPicFile();
            mutex = true;
        }

        // 大屏幕对外正式播放
        private void playList(object sender, RoutedEventArgs e)
        {
            // 关闭已有的播放屏幕
            Model.ScreenManager.closeScreen();
            // 创建新屏幕
            scr = new Screen();
            scr.Show();
            scr.playPicture();
            // 对外播放时暂停预览界面的播放
            timer.Stop();
        }

        // 退出当前播放
        private void quitPlay(object sender, RoutedEventArgs e)
        {
            Model.ScreenManager.closeScreen();
            // 退出对外播放后恢复预览界面的播放
            timer.Start();
        }
    }
}
